package chapter18;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.*;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/3/28 8:53
 */
public class ZipCompress {
    public static void main(String[] args) throws IOException {
        FileOutputStream f = new FileOutputStream("test.zip");
        CheckedOutputStream cos = new CheckedOutputStream(f, new Adler32());
        ZipOutputStream zipOut = new ZipOutputStream(cos);
        zipOut.setComment("test for java zip");
        BufferedOutputStream out = new BufferedOutputStream(zipOut);
        String[] files = {"file1.doc", "file2.jpg", "file3.exe"};
        for (String file : files) {
            System.out.println("write file " + file);
            BufferedReader reader = new BufferedReader(new FileReader(file));
            zipOut.putNextEntry(new ZipEntry(file));
            int c = -1;
            while ((c = reader.read()) != -1) {
                out.write(c);
            }
            reader.close();
            out.flush();
        }
        out.close();
        System.out.println("Checksum:" + cos.getChecksum().getValue());

        System.out.println("decompress files");
        FileInputStream fi = new FileInputStream("test.zip");
        CheckedInputStream checkedInputStream = new CheckedInputStream(fi, new Adler32());
        ZipInputStream zis = new ZipInputStream(checkedInputStream);
        BufferedInputStream inputStream = new BufferedInputStream(zis);
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("reading file " + entry);
            int x;
            while ((x = inputStream.read()) != -1) {
                System.out.println(x);
            }
        }

        System.out.println("Checksum:" + checkedInputStream.getChecksum());

        inputStream.close();

        ZipFile zipFile = new ZipFile("test.zip");
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry1 = entries.nextElement();
            System.out.println("file:" + entry1);
        }

    }
}
